<script lang="ts" setup>
import type { UpdateReceivingAttachmentInfoRequest } from '@/types/api/order'
import type { FileObject } from '@/types/api/public'
import type { Ref } from 'vue'
import { orderApi } from '@/request/api'
import { useConsole, useHideLoading, useLoading, useModal, useNav, useNavBack, useRouteGuard } from '@/utils'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { to } from 'await-to-js'
import { reactive, ref } from 'vue'
import { any as zany, array as zarray, object as zobject, record as zrecord, string as zstring } from 'zod'

const oid = ref() as Ref<number>
const mode = ref() as Ref<number> // 0 手机  1 电动车
const type = ref('') // 全新 二手

const form = reactive<Record<string, FileObject[]>>({
  currentContract: [],
  orderConfirmed: [],
  newMachineOpened: [],
  other: [],
  identityAndVehicleCertificatePhotos: [],
  lockSystemCompletion: [],
})

onLoad(async (query) => {
  const zparse = zobject({
    oid: zstring().regex(/^\d+$/).transform(Number),
    mode: zstring().regex(/^\d+$/).transform(Number),
    type: zstring(),
  }).safeParse(query)
  if (!zparse.success) {
    return await useRouteGuard()
  }

  oid.value = zparse.data.oid
  mode.value = zparse.data.mode
  type.value = zparse.data.type

  getInfo()
})

onUnload(() => {
  uni.$emit('refreshOrderDetail')
})

async function getInfo() {
  useLoading(true)
  const [err, res] = await to(
    orderApi.getReceivingAttachment({ oid: oid.value }),
  )
  useHideLoading()
  if (err) {
    return
  }

  form.currentContract = res.currentContract ?? []
  form.orderConfirmed = res.orderConfirmed ?? []
  form.newMachineOpened = res.newMachineOpened ?? []
  form.other = res.other ?? []
  form.identityAndVehicleCertificatePhotos = res.identityAndVehicleCertificatePhotos ?? []
  form.lockSystemCompletion = res.lockSystemCompletion ?? []
}

async function handleSubmit() {
  const scheme = [
    zobject({
      currentContract: zarray(zrecord(zany())).min(1, { message: '请上传现场合同照片' }),
      orderConfirmed: zarray(zrecord(zany())).min(1, { message: '请上传订单确认视频' }),
      newMachineOpened: (() => [
        zarray(zrecord(zany())).min(1, { message: '请上传新机拆封视频' }),
        zarray(zrecord(zany())).optional(),
      ][['全新', '二手'].indexOf(type.value)])(),
      other: zarray(zrecord(zany())),
    }),
    zobject({
      identityAndVehicleCertificatePhotos: zarray(zrecord(zany())).min(1, { message: '请上传手持身份证和电动车合格证照片' }),
      lockSystemCompletion: zarray(zrecord(zany())).min(1, { message: '请上传锁车完成后锁车系统图片' }),
    }),
  ][mode.value]
  const zparse = scheme.safeParse(form)
  if (!zparse.success) {
    await useModal({
      title: '提示',
      content: zparse.error.issues[0].message,
      showCancel: false,
      confirmText: '好的',
    })
    return
  }

  useConsole?.log(zparse.data)

  useLoading(true)
  const [err] = await to(
    orderApi.updateReceivingAttachment({
      oid: oid.value,
      ...zparse.data as Omit<UpdateReceivingAttachmentInfoRequest, 'oid'>,
    }),
  )
  useHideLoading()
  if (err) {
    return
  }

  await useModal({
    title: '提示',
    content: '提交成功',
    showCancel: false,
    confirmText: '返回',
  })

  useNavBack()

  // useRelaunch('/attachment/result', {
  //   status: 'success',
  //   title: '操作成功',
  //   subtitle: '请返回上一页',
  // })

  // my.alert({
  //   title: '提示',
  //   content: '提交成功',
  //   buttonText: '返回上一页',
  //   success: () => {
  //     my.navigateBack()
  //   },
  // })
}

function handleNavHelp(key: string) {
  useNav('/attachment/help', { anchor: `receiving_${key}` })
}
</script>

<template>
  <view class="px-30px pt-20px">

    <template v-if="mode === 0">
      <view class="rd-16px bg-white px-20px pb-20px">
        <view class="h-80px flex items-center pl-10px">
          <view class="text-28px text-#3">现场合同照片</view>
          <view class="ml-10px text-24px text-[red]">(必填)</view>
          <view class="text-theme-primary ml-a text-28px lh-50px" @click="handleNavHelp('currentContract')">查看指引</view>
        </view>
        <cm-media-list-slim :file-list="form.currentContract"></cm-media-list-slim>
      </view>

      <!-- <view class="mt-10px rd-16px bg-white px-20px pb-20px">
      <view class="h-80px flex items-center pl-10px">
        <view class="text-28px text-#3">收货回执单</view>
        <view class="ml-10px text-24px text-[red]">(必填)</view>
      </view>
      <cm-media-list-slim :file-list="form.receivingReceipt"></cm-media-list-slim>
    </view> -->

      <view class="mt-10px rd-16px bg-white px-20px pb-20px">
        <view class="h-80px flex items-center pl-10px">
          <view class="text-28px text-#3">订单确认视频</view>
          <view class="ml-10px text-24px text-[red]">(必填)</view>
          <view class="text-theme-primary ml-a text-28px lh-50px" @click="handleNavHelp('orderConfirmed')">查看指引</view>
        </view>
        <cm-media-list-slim :file-list="form.orderConfirmed"></cm-media-list-slim>
      </view>

      <view v-if="type !== '二手'" class="mt-10px rd-16px bg-white px-20px pb-20px">
        <view class="h-80px flex items-center pl-10px">
          <view class="text-28px text-#3">新机拆封视频</view>
          <view class="ml-10px text-24px text-[red]">(必填)</view>
          <view class="text-theme-primary ml-a text-28px lh-50px" @click="handleNavHelp('newMachineOpened')">查看指引</view>
        </view>
        <cm-media-list-slim :file-list="form.newMachineOpened"></cm-media-list-slim>
      </view>

      <view class="mt-10px rd-16px bg-white px-20px pb-20px">
        <view class="h-80px flex items-center pl-10px">
          <view class="text-28px text-#3">其他材料</view>
        </view>
        <cm-media-list-slim :file-list="form.other"></cm-media-list-slim>
      </view>
    </template>

    <template v-if="mode === 1">
      <view class="mt-10px rd-16px bg-white px-20px pb-20px">
        <view class="h-80px flex items-center pl-10px">
          <view class="text-28px text-#3">手持身份证和电动车合格证照片</view>
          <view class="ml-10px text-24px text-[red]">(必填)</view>
          <view class="text-theme-primary ml-a text-28px lh-50px" @click="handleNavHelp('identityAndVehicleCertificatePhotos')">查看指引</view>
        </view>
        <cm-media-list-slim :file-list="form.identityAndVehicleCertificatePhotos"></cm-media-list-slim>
      </view>

      <view class="mt-10px rd-16px bg-white px-20px pb-20px">
        <view class="h-80px flex items-center pl-10px">
          <view class="text-28px text-#3">锁车完成后锁车系统图片</view>
          <view class="ml-10px text-24px text-[red]">(必填)</view>
          <view class="text-theme-primary ml-a text-28px lh-50px" @click="handleNavHelp('lockSystemCompletion')">查看指引</view>
        </view>
        <cm-media-list-slim :file-list="form.lockSystemCompletion"></cm-media-list-slim>
      </view>
    </template>

    <view class="safe-pb-15px">
      <view class="h-115px"></view>
    </view>
  </view>

  <view class="fixed bottom-0 w-full flex bg-white pt-15px safe-pb-15px">
    <view class="btn-primary-black mx-a w-600px text-36px lh-80px" @click="handleSubmit">提交</view>
  </view>
</template>

<style lang="less" scoped></style>
